package msdelete;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.MajorDao;
import model.dao.SurveyItemDao;
import model.entity.Major;
import model.entity.SurveyItem;

/**
 * Servlet implementation class GetMSItemDele
 */
@WebServlet("/GetMSItemDele")
public class GetMSItemDele extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetMSItemDele() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try {
			Enumeration<String> itemid = request.getParameterNames();
			String condit = (String) request.getParameter("condit");

			SurveyItem suritem = new SurveyItem();

			for (int i = 0; i < 2; i++) {
				String paraName = (String) itemid.nextElement();
				String paraVal = request.getParameter(paraName);
				System.out.println(paraName + " " + paraVal);
				if (paraVal != "") {
					switch (i) {
					case 0:
						suritem.setId(Integer.valueOf(paraVal));
						break;
					case 1:
					    suritem.setName(paraVal);
						break;
					default:
						break;
					}
				}
			}

			SurveyItemDao td = new SurveyItemDao();
			List<SurveyItem> list = td.getRanSelect(suritem, condit);
			
			if(list.size()==0){
				throw new Exception("empty");
			}

			String str = "[";
			for (SurveyItem tea : list) {
				str += "{\"ID\":" + tea.getId() + ",\"Name\":\"" + tea.getName() + "\"},";
			}

			str = str.substring(0, str.length() - 1);
			str += "]";
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
            out.print(str);
            
            td.delete(suritem, condit);
		} catch (Exception e) {
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			if(e.getMessage()=="empty"){
				out.print("empty");
			}else{
				out.print("unsuccessful");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
